import React, { useEffect, useState } from 'react';
import type { FC } from 'react';
import { useAppSelector, useAppDispatch } from '../../store/hooks';
import { LeftOutline, EyeOutline, EyeInvisibleOutline } from 'antd-mobile-icons';
import { Switch, Dialog, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { setUsers } from '../../store/slices/userListSlice';
import type { UserListItem } from '../../store/slices/userListSlice';
import './index.css';
const AuthSetting: FC = ({ }) => {
  const { users } = useAppSelector((state) => state.userList);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [visiblePasswords, setVisiblePasswords] = useState<{ [key: number]: boolean }>({});
  const [visibleEmails, setVisibleEmails] = useState<{ [key: number]: boolean }>({});

  // 深拷贝users数据到本地状态
  const [localUsers, setLocalUsers] = useState<UserListItem[]>([]);

  console.log('Redux users:', users);
  console.log('Local users:', localUsers);

  // 深拷贝函数
  const deepCopyUsers = (users: UserListItem[]): UserListItem[] => {
    return users.map(user => ({
      email: user.email,
      pwd: user.pwd,
      isAdmin: user.isAdmin
    }));
  };

  // 初始化本地状态
  useEffect(() => {
    const copiedUsers = deepCopyUsers(users);
    setLocalUsers(copiedUsers);
    console.log('深拷贝users数据:', copiedUsers);

    // 调试：检查localStorage中的数据
    try {
      const persistedState = localStorage.getItem('persist:root');
      if (persistedState) {
        const parsed = JSON.parse(persistedState);
        console.log('localStorage中的完整数据:', parsed);
        if (parsed.userList) {
          const userListData = JSON.parse(parsed.userList);
          console.log('localStorage中的userList数据:', userListData);
        }
      } else {
        console.log('localStorage中没有persist:root数据');
      }
    } catch (error) {
      console.error('读取localStorage数据失败:', error);
    }
  }, [users]);

  // 切换密码可见性
  const togglePasswordVisibility = (index: number) => {
    setVisiblePasswords(prev => ({
      ...prev,
      [index]: !prev[index]
    }));
  };

  // 切换邮箱可见性
  const toggleEmailVisibility = (index: number) => {
    setVisibleEmails(prev => ({
      ...prev,
      [index]: !prev[index]
    }));
  };

  // 切换管理员权限 - 只更新本地状态
  const toggleAdminStatus = (index: number, checked: boolean) => {
    setLocalUsers(prevUsers =>
      prevUsers.map((user, i) =>
        i === index ? { ...user, isAdmin: checked } : user
      )
    );
  };

  // 保存更改到redux
  const saveChanges = () => {
    dispatch(setUsers(localUsers));
    Toast.show({
      content: '权限设置已保存',
      afterClose: () => {
        navigate(-1);
      }
    });
  };

  // 检查是否有更改
  const hasChanges = () => {
    return JSON.stringify(users) !== JSON.stringify(localUsers);
  };


  // 掩码处理函数
  const maskText = (text: string, visible: boolean) => {
    if (visible) return text;
    return '*'.repeat(Math.min(text.length, 8));
  };

  return (
    <div className="auth">
      <div className="auth-header">
        <div className="auth-header-left" onClick={() => {
          if (hasChanges()) {
            Dialog.show({
              title: '确认操作',
              content: '检测到未保存的更改，是否保存当前设置？',
              closeOnAction: true,
              actions: [
                {
                  key: 'cancel',
                  text: '不保存',
                  onClick: () => {
                    navigate(-1);
                  }
                },
                {
                  key: 'save',
                  text: '保存',
                  bold: true,
                  onClick: () => {
                    saveChanges();
                  }
                },
              ],
            });
          } else {
            navigate(-1);
          }
        }}>
          <div className="auth-header-left-icon">
            <LeftOutline width={25} height={25} />
          </div>
        </div>
        <div className="auth-header-center">
          <h2> 权限管理</h2>
        </div>
        <div className="auth-header-right">
          &emsp;
        </div>
      </div>
      <div className="auth-main">
        {
          localUsers.map((item, index) => {
            return (
              <div key={index} className="auth-main-item">
                <div className="user-info">
                  <div className="user-field">
                    <label>邮箱:</label>
                    <div className="field-content">
                      <span className="field-text">
                        {maskText(item.email, visibleEmails[index])}
                      </span>
                      <div
                        className="visibility-toggle"
                        onClick={() => toggleEmailVisibility(index)}
                      >
                        {visibleEmails[index] ?
                          <EyeInvisibleOutline fontSize={16} /> :
                          <EyeOutline fontSize={16} />
                        }
                      </div>
                    </div>
                  </div>

                  <div className="user-field">
                    <label>密码:</label>
                    <div className="field-content">
                      <span className="field-text">
                        {maskText(item.pwd, visiblePasswords[index])}
                      </span>
                      <div
                        className="visibility-toggle"
                        onClick={() => togglePasswordVisibility(index)}
                      >
                        {visiblePasswords[index] ?
                          <EyeInvisibleOutline fontSize={16} /> :
                          <EyeOutline fontSize={16} />
                        }
                      </div>
                    </div>
                  </div>

                  <div className="user-field admin-field">
                    <label>管理员权限:</label>
                    <div className="field-content">
                      <Switch
                        checked={item.isAdmin}
                        onChange={(checked) => toggleAdminStatus(index, checked)}
                      />
                    </div>
                  </div>
                </div>
              </div>
            );
          })
        }
      </div>
    </div>
  );
};

export default AuthSetting;